// import OSS from 'ali-oss';
import { LoginUser } from './types';
import axios, { AxiosInstance, AxiosProgressEvent, InternalAxiosRequestConfig } from 'axios';
import { isArray, isNull } from './utils/utils';
class Main {
    api: AxiosInstance = axios.create({
        baseURL: 'https://dev3.zhisuoyi.net/api/',
        // baseURL: 'http://192.168.1.201:8080/',
        timeout: 120000,
        onUploadProgress(progressEvent: AxiosProgressEvent) {
            if (main.uploadProgress) {
                main.uploadProgress(progressEvent.loaded, progressEvent.total ?? 0);
            }
        },
    });
    uploadProgress?: (loaded: number, total: number) => void;
    /** 各页面当前页码 按页面标签区分 */
    currPageNum: { [x: string]: number } = {};
    /** 各页面当前记录数量 按页面标签区分 */
    currPageSize: { [x: string]: number } = {};
    /** 各页面当前搜索状态 按页面标签区分 */
    currPageState: { [x: string]: { [x: string]: any } } = {};
    defaultPageSize: number = 12;
    defaultPageSizeOptions: number[] = [10, 12, 20, 30, 50, 100];
    user?: LoginUser;
    permissions?: string[];
    roles?: string[];
    loginKey?: string | null;
    pageId?: string | null;
    ossBasePath = 'importExcel/';
    // aliOssClient = new OSS({
    //     region: 'oss-cn-shanghai',
    //     accessKeyId: 'LTAI5tCWfdjtG1iyF1LYDmLN',
    //     accessKeySecret: 'FQHev3RQRzdqIYvXBkoaI61FCiKzBG',
    //     bucket: 'jk-card',
    //     endpoint: 'oss-cn-shanghai.aliyuncs.com',
    // });
    init() {
        this.api.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
            let url = config.url;
            if (config.method === 'get' && config.params) {
                url += '?';
                Object.keys(config.params).forEach((k: string) => {
                    let _value = config.params[k];
                    if (typeof _value === 'object' && isArray(_value)) {
                        _value = (_value as Array<any>)
                            .map((v, i) => (isNull(v) ? '' : `${k}[${i}]=${encodeURIComponent(v)}`))
                            .join('&');
                        url += `${_value}&`;
                    } else if (typeof _value === 'object') {
                        _value = Object.keys(_value)
                            .map((_k) =>
                                isNull(_value[_k]) ? '' : `${encodeURIComponent(`${k}[${_k}]`)}=${encodeURIComponent(`${_value[_k]}`)}`
                            )
                            .join('&');

                        url += `${_value}&`;
                    } else {
                        if (!isNull(_value)) {
                            url += `${k}=${encodeURIComponent(_value)}&`;
                        }
                    }
                });
                url = url?.substring(0, url.length - 1);
                config.params = {};
                config.url = url;
            }
            return config;
        }, undefined);
        this.api.interceptors.response.use((response) => {
            function getPageId(url: string): string {
                const reg = /pageId=([^&]+)/;
                const match = url.match(reg);
                return match ? match[1] : '';
            }
            if (response.data.code === 401) {
                const href = window.location.href;
                const pageId = getPageId(href);
                window.parent.postMessage({ type: 'token', id: pageId }, '*');
            }
            return response;
          });
        let token = this.token;
        if (token) {
            this.api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        }
    }
    token?: string;
    /** 设置当前页码 同时清除别的页面页码和检索条件 */
    setPageNum(tag: string, num: number, params?: any) {
        if (!this.currPageNum[tag]) {
            this.currPageNum[tag] = 1;
        }
        this.currPageNum[tag] = num;
        if (!this.currPageState[tag]) {
            this.currPageState[tag] = {};
        }
        this.currPageState[tag] = params;
    }
}

const main = new Main();
export default main;
